package com.kensure.shike.zhang.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import co.kensure.exception.BusinessExceptionUtil;
import co.kensure.exception.ParamUtils;
import co.kensure.frame.JSBaseService;
import co.kensure.mem.CollectionUtils;
import co.kensure.mem.DateUtils;
import co.kensure.mem.ListUtils;
import co.kensure.mem.MapUtils;
import co.kensure.mem.PageInfo;

import com.kensure.basekey.BaseKeyService;
import com.kensure.shike.chongzhi.query.SKZhangQuery;
import com.kensure.shike.user.model.SKUser;
import com.kensure.shike.user.model.SKUserFR;
import com.kensure.shike.user.service.SKUserFRService;
import com.kensure.shike.user.service.SKUserService;
import com.kensure.shike.zhang.dao.SKUserZhangDao;
import com.kensure.shike.zhang.model.SKUserZhang;

/**
 * 用户余额流水服务实现类
 * 
 * @author fankd created on 2018-9-9
 * @since
 */
@Service
public class SKUserZhangService extends JSBaseService {

	@Resource
	private SKUserZhangDao dao;

	@Resource
	private BaseKeyService baseKeyService;

	@Resource
	private SKUserYueService sKUserYueService;
	@Resource
	private SKUserService sKUserService;
	@Resource
	private SKUserFRService sKUserFRService;

	public SKUserZhang selectOne(Long id) {
		return dao.selectOne(id);
	}

	public List<SKUserZhang> selectByIds(Collection<Long> ids) {
		return dao.selectByIds(ids);
	}

	public List<SKUserZhang> selectByWhere(Map<String, Object> parameters) {
		return dao.selectByWhere(parameters);
	}

	public long selectCountByWhere(Map<String, Object> parameters) {
		return dao.selectCountByWhere(parameters);
	}

	public boolean insert(SKUserZhang obj) {
		super.beforeInsert(obj);
		obj.setId(baseKeyService.getKey("sk_user_zhang"));
		if (obj.getJinbi() == null) {
			obj.setJinbi(0D);
		}
		if (obj.getYue() == null) {
			obj.setYue(0D);
		}
		if (obj.getDbyue() == null) {
			obj.setDbyue(0D);
		}
		if (obj.getWxyue() == null) {
			obj.setWxyue(0D);
		}
		return dao.insert(obj);
	}

	public boolean update(SKUserZhang obj) {
		super.beforeUpdate(obj);
		return dao.update(obj);
	}

	public boolean updateByMap(Map<String, Object> params) {
		return dao.updateByMap(params);
	}

	/**
	 * 用户帐
	 * 
	 * @return
	 */
	public List<SKUserZhang> selectByUser(SKUser user, Integer inorout, Integer status) {
		Map<String, Object> parameters = MapUtils.genMap("userid", user.getId(), "orderby", "updated_time desc");
		if (inorout != null) {
			parameters.put("inorout", inorout);
		}
		if (status != null) {
			parameters.put("status", status);
		}
		return selectByWhere(parameters);
	}

	/**
	 * 用户帐分佣帐
	 * 
	 * @return
	 */
	public List<SKUserZhang> selectByUserAndBusi(SKUser user) {
		Map<String, Object> parameters = MapUtils.genMap("userid", user.getId(), "busitypeidlist", ListUtils.toLongCol("109,110,119,120,121,122,131,132,199"), "orderby", "updated_time desc");
		List<SKUserZhang> list = selectByWhere(parameters);
		if (CollectionUtils.isNotEmpty(list)) {
			for (SKUserZhang userzhang : list) {
				SKUserFR fr = sKUserFRService.selectByOrderid(userzhang.getBusiid(), "DD");
				if (fr != null) {
					SKUser fuser = sKUserService.selectOne(fr.getUserid());
					if (fuser != null) {
						fr.setUserName(fuser.getNickname());
					}
					userzhang.setFr(fr);
				}
			}
		}
		return list;
	}

	/**
	 * 分润未到账佣金列表
	 * 
	 * @return
	 */
	public List<SKUserZhang> selectFrList(String frid, List<Long> bysitypeidList) {
		Map<String, Object> parameters = MapUtils.genMap("busiid", frid, "busitypeidlist", bysitypeidList, "status", 0);
		List<SKUserZhang> list = selectByWhere(parameters);
		return list;
	}

	/**
	 * 管理员 获取账务流水记录,分页
	 */
	public List<SKUserZhang> selectAllZhangList(SKZhangQuery query, PageInfo page) {
		Map<String, Object> parameters = MapUtils.bean2Map(query, true);
		parameters.put("orderby", "created_time desc");
		MapUtils.putPageInfo(parameters, page);
		List<SKUserZhang> list = selectByWhere(parameters);
		if (CollectionUtils.isNotEmpty(list)) {
			for (SKUserZhang zhang : list) {
				SKUser user = sKUserService.selectOne(zhang.getUserid());
				zhang.setUser(user);
			}
		}
		return list;
	}

	/**
	 * 管理员 获取账务流水,总数
	 */
	public long selectAllZhangCount(SKZhangQuery query) {
		Map<String, Object> parameters = MapUtils.bean2Map(query, true);
		return selectCountByWhere(parameters);
	}

	/**
	 * 新增账款，只是无效的，没有变动余额
	 * 
	 * @param obj
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void add(SKUserZhang obj) {
		ParamUtils.isBlankThrewException(obj.getUserid(), "用户不能为空");
		if (obj.getYue() == null) {
			obj.setYue(0D);
		}
		if (obj.getYue() < 0) {
			BusinessExceptionUtil.threwException("金额不能小于0");
		}
		obj.setStatus(0);
		// 业务类型id <100以内是支出，<=100-<=200是收入, 1是销售消费 3是会员费
		if (obj.getBusitypeid() < 100) {
			obj.setInorout(-1);
		} else if (obj.getBusitypeid() <= 200) {
			obj.setInorout(1);
		}
		insert(obj);
	}

	/**
	 * 提交账款，让他把状态变成1,并且变动余额
	 */
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void commit(Long zhangid) {
		SKUserZhang zhang = selectOne(zhangid);
		if (zhang.getStatus() == 0) {
			sKUserYueService.updateYue(zhang.getId());
		} else {
			BusinessExceptionUtil.threwException("账单已过期");
		}
	}

	/**
	 * 计算所有的钱
	 * 
	 * @param parameters
	 * @return
	 */
	private Double sumAllYueByWhere(Map<String, Object> parameters) {
		return dao.sumAllYueByWhere(parameters);
	}

	/**
	 * 30天内的财务数据
	 */
	public List<Map<String, Object>> caiwushuju() {
		List<Map<String, Object>> mapList = new ArrayList<>();
		Date now = new Date();
		// 销售收入
		List<Long> xiaoshoubt = ListUtils.toLongCol("1");
		// 会员收入
		List<Long> huiyuanbt = ListUtils.toLongCol("3");
		// 销售分成
		List<Long> xiaoshoufcbt = ListUtils.toLongCol("119,120");
		// 会员分成
		List<Long> huiyuanfcbt = ListUtils.toLongCol("109,110");
		// 退换货支出
		List<Long> tuihuobt = ListUtils.toLongCol("102,103");

		for (int day = 0; day < 30; day++) {
			Date date = DateUtils.getPastDay(now, -day);
			// 销售收入
			Double xssr = oneDayDate(date, xiaoshoubt);
			// 会员收入
			Double hysr = oneDayDate(date, huiyuanbt);

			// 销售分成
			Double xsfc = oneDayDate(date, xiaoshoufcbt);
			// 会员分成
			Double hyfc = oneDayDate(date, huiyuanfcbt);
			// 退换货支出
			Double thhzc = oneDayDate(date, tuihuobt);

			String days = DateUtils.format(date, DateUtils.DAY_FORMAT);
			Map<String, Object> oneday = MapUtils.genMap("id", days, "xssr", xssr, "hysr", hysr, "xsfc", xsfc, "hyfc", hyfc, "thhzc", thhzc);
			mapList.add(oneday);
		}
		return mapList;
	}

	/**
	 * 某天的财务数据情况
	 */
	private Double oneDayDate(Date date, List<Long> busitypeidlist) {
		String startTime = DateUtils.formatDateStart(date);
		String endTime = DateUtils.formatDateEnd(date);
		Map<String, Object> parameters = MapUtils.genMap("busitypeidlist", busitypeidlist, "status", 1, "startCreatedTime", startTime, "endCreatedTime", endTime);
		Double total = sumAllYueByWhere(parameters);
		if (total == null) {
			total = 0D;
		}
		return total;
	}

	/**
	 * 根据业务主键获取用户帐
	 * 
	 * @return
	 */
	private SKUserZhang getBusi(Long userid, Long busitypeid, Long busiid) {
		SKUserZhang zhang = null;
		Map<String, Object> parameters = MapUtils.genMap("userid", userid, "busiid", busiid, "busitypeid", busitypeid, "billno", "0");
		List<SKUserZhang> list = selectByWhere(parameters);
		if (CollectionUtils.isNotEmpty(list)) {
			zhang = list.get(0);
		}
		return zhang;
	}

}
